/**
 * Created by neal on 11/22/16.
 */
var Config = {
    createUrl: '/api/admin/goods',
    updateUrl: '/api/goods',
    deleteUrl: '/api/goods',
    selectUrl: '/api/goods',
    selectCompanyUrl: '/api/admin/goodsSpecifications'
};

var ConfigCategory = {
    createUrl: '/admin/categories/post',
    updateUrl: '/admin/categories/update',
    deleteUrl: '/admin/categories/delete',
    selectUrl: '/api/categories'
};

var ConfigType = {
    createUrl: '/api/admin/goodsType/post',
    updateUrl: '/api/admin/goodsType/update',
    deleteUrl: '/api/admin/goodsType/delete',
    selectUrl: '/api/admin/goodsType/get'
};

var ConfigAttribute = {
    selectUrl: '/api/goodsAttribute'
};
var ConfigAttributeLink = {
    createUrl: '/api/goodsAttributeLink',
};
var ConfigGoodsTypeCustom = {
    selectUrl: '/api/admin/goodsTypeCustom',
}


$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});

var ue = UE.getEditor('editor');
var ueAlbum = UE.getEditor('editorAlbum', {
    toolbars: [
        ['simpleupload','insertimage']
    ],
    autoHeightEnabled: true,
    autoFloatEnabled: true
});

ue.ready(function () {
    ue.execCommand('serverparam', {
        'goodsId': 0,
        'imageType': 0
    });
});
ueAlbum.ready(function () {
    ueAlbum.execCommand('serverparam', {
        'goodsId': 0,
        'imageType': 1
    });
});

$().ready(function () {
    $('#collapseOne').collapse('hide');
    $('#collapseTwo').collapse('hide');
    $("#datepicker").datepicker({keyboardNavigation: !1, forceParse: !1, autoclose: !0});
    $.ajax(
        {
            url: ConfigCategory.selectUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true">顶级分类</option>');
                data.data.map(function (category) {
                    categories.push('<option value="');
                    categories.push(category.categoryId);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(category.categoryName);
                    categories.push('</option>');
                });
                $("#categoryId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    $.ajax(
        {
            url: Config.selectCompanyUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="" hassubinfo="true">品牌</option>');
                data.data.map(function (specifications) {
                    categories.push('<option value="');
                    categories.push(specifications.id);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(specifications.name);
                    categories.push('</option>');
                });
                $("#goodsWeight").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    $.ajax(
        {
            url: ConfigType.selectUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true"  >商品类型</option>');
                data.data.map(function (category) {
                    categories.push('<option value="');
                    categories.push(category.typeId);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(category.typeName);
                    categories.push('</option>');
                });
                $("#typeId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    $.ajax(
        {
            url: "/api/admin/goodsSpecifications",
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true"  >商品品牌</option>');
                data.data.map(function (category) {
                    categories.push('<option value="');
                    categories.push(category.id);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(category.name);
                    categories.push('</option>');
                });
                $("#goodsWeight").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    $.ajax(
        {
            url: ConfigCategory.selectUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true">顶级分类</option>');
                data.data.map(function (category) {
                    categories.push('<option value="');
                    categories.push(category.categoryId);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(category.categoryName);
                    categories.push('</option>');
                });
                $("#goodsBrandId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    // providers
    $.ajax(
        {
            url: Config.selectCompanyUrl,
            type: "GET",
            // data: {companyType: 8},
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true">供货商</option>');
                data.data.map(function (company) {
                    categories.push('<option value="');
                    categories.push(company.companyId);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(company.companyName);
                    categories.push('</option>');
                });
                $("#goodsProviderId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    $("#goodsProviderId").change(function () {
        $.ajax(
            {
                url: ConfigGoodsTypeCustom.selectUrl,
                type: "GET",
                data:{companyId:$("#goodsProviderId option:selected").val()},
                dataType: "json",
                async: false,
                success: function (data, textStatus, jqXHR) {
                    var categories = [];
                    categories.push('<option value="0" hassubinfo="true">请选择分类</option>');
                    data.data.map(function (goodsTypeCustom) {
                        categories.push('<option value="');
                        categories.push(goodsTypeCustom.id);
                        categories.push('" ');
                        categories.push('hassubinfo="true">');
                        categories.push(goodsTypeCustom.name);
                        categories.push('</option>');
                    });
                    $("#customTypeId").html(categories.join(''));
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
    })


    $.ajax({
        url: '/api/admin/categories',
        type: "GET",
        data:{level:1},
        dataType: "json",
        async: false,
        success: function (data, textStatus, jqXHR) {
            var categories = [];
            categories.push('<option value="0" hassubinfo="true">请选择分类</option>');
            data.data.map(function (category) {
                categories.push('<option value="');
                categories.push(category.id);
                categories.push('" ');
                categories.push('hassubinfo="true">');
                categories.push(category.name);
                categories.push('</option>');
            });
            $("#cateLevel1").html(categories.join(''));
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error(errorThrown, textStatus);
        }
    });

    $("#cateLevel1").change(function () {
        $.ajax({
            url: '/api/admin/categories',
            type: "GET",
            data:{level:2,parentId:$("#cateLevel1 option:selected").val()},
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true">请选择分类</option>');
                data.data.map(function (goodsTypeCustom) {
                    categories.push('<option value="');
                    categories.push(goodsTypeCustom.id);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(goodsTypeCustom.name);
                    categories.push('</option>');
                });
                $("#cateLevel2").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    })


    $("#cateLevel2").change(function () {
        $.ajax({
            url: '/api/admin/categories',
            type: "GET",
            data:{level:3,parentId:$("#cateLevel2 option:selected").val()},
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true">请选择分类</option>');
                data.data.map(function (goodsTypeCustom) {
                    categories.push('<option value="');
                    categories.push(goodsTypeCustom.id);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(goodsTypeCustom.name);
                    categories.push('</option>');
                });
                $("#cateLevel3").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    })

    // jQuery.validator.addMethod('selectcheck', function (value) {
    //     return (value != '0');
    // }, "请选择分类");
    jQuery.validator.addMethod('selectcheck1', function (value) {
        return (value != '0');
    }, "请选择供货商");
    $('#submitCategoryCreate').click(function () {
        if ($("#goodsPayType").val() == 0) {
            if (Number($("input[id=goodsScreenPrice]").val())  <  Number($("input[id=goodsRealPrice]").val())){
                toastr.error("卖出价必须大于进货价，请输入正确的价格！");
            return false;
            }
        }
        if ($("#goodsScreenPrice").val() <= 0 || $("#goodsScore").val() < 0 || $("#goodsRealPrice").val() <= 0 || $("#goodsStock").val() < 0 || $("#giveScore").val() < 0) {
                toastr.warning("请正确输入信息，价格单位不能 <=0,积分库存单位不能 <0","警告");
                return false;
        }
        $("#ajaxform").validate({
            rules: {
                // categoryId: {
                //     selectcheck: true
                // },
                // customTypeId: {
                //     selectcheck: true
                // },
                goodsProviderId: {
                    selectcheck1: true
                }
            }
        });
            if ($('#ajaxform').valid()) {
                if($("#cateLevel3").val() != 0){
                    $("#cateId").val($("#cateLevel3").val());
                } else if($("#cateLevel2").val() != 0){
                    $("#cateId").val($("#cateLevel2").val());
                } else if($("#cateLevel1").val() != 0){
                    $("#cateId").val($("#cateLevel1").val());
                }
                var postData = $('#ajaxform').serializeArray();

                $.ajax(
                    {
                        url: Config.createUrl,
                        type: "POST",
                        data: postData,
                        dataType: "json",
                        success: function (data, textStatus, jqXHR) {
                            CONST_GLOBAL_GOODS_ID = data.data.goodsId;
                            // $.ajax({
                            //     url:"/api/admin/rebateRatio",
                            //     type: "POST",
                            //     data: {goodsId:CONST_GLOBAL_GOODS_ID,oneLevel:oneLevel,twoLevel:twoLevel,
                            //         areaLevel:areaLevel,cityLevel:cityLevel,provinceLevel:provinceLevel,rtLevel:rtLevel},
                            //     dataType: "json",
                            //     success: function (data, textStatus, jqXHR) {
                            //         toastr.success("返利比例创建成功!", data.title);
                            //     }
                            // });
                            ue.ready(function () {
                                ue.execCommand('serverparam', {
                                    'goodsId': CONST_GLOBAL_GOODS_ID,
                                    'imageType': 0
                                });
                            });
                            ueAlbum.ready(function () {
                                ueAlbum.execCommand('serverparam', {
                                    'goodsId': CONST_GLOBAL_GOODS_ID,
                                    'imageType': 1
                                });
                            });
                            toastr.success(data.msg, data.title);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            toastr.error(errorThrown, textStatus);
                        }
                    });
            }
            return false;
    });
    $('#submitCategoryDetail').click(function () {
        var img;
        var str = ue.getContent();
        var imgReg = /<img.*?(?:>|\/>)/gi;
        var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
        var arr = str.match(imgReg);  // arr 为包含所有img标签的数组

        for (var i = 0; i < arr.length; i++) {
            //获取图片地址
            var src = arr[i].match(srcReg);
            if(i >= 1){
                img = img + "," + src[1]
            } else {
                img = src[1]
            }
        }
        $.ajax(
            {
                url: Config.updateUrl,
                type: "PUT",
                data: {goodsId: CONST_GLOBAL_GOODS_ID, goodsDetail: getContent()},
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    //toastr.success(data.msg, data.title);
                    $.ajax({
                        url: '/api/admin/goodsAlbum/update',
                        type: "PUT",
                        data: {goodsId: CONST_GLOBAL_GOODS_ID, detailePictureUrl:img},
                        dataType: "json",
                        success: function (data, textStatus, jqXHR) {
                            toastr.success(data.msg, data.title);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            toastr.error(errorThrown, textStatus);
                        }
                    });
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
        return false;
    });

    $('#submitAlbum').click(function () {
        var img;
        var str = ueAlbum.getContent();
        var imgReg = /<img.*?(?:>|\/>)/gi;
        var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
        var arr = str.match(imgReg);  // arr 为包含所有img标签的数组
        var goodsThum;

        for (var i = 0; i < arr.length; i++) {
            //获取图片地址
            var src = arr[i].match(srcReg);
            if(i >= 1){
                img = img + "," + src[1]
            } else {
                img = src[1];
                goodsThum = src[1];
            }
        }
        $.ajax({
            url: Config.updateUrl,
            type: "PUT",
            data: {goodsId: CONST_GLOBAL_GOODS_ID, goodsThum: goodsThum},
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                //toastr.success(data.msg, data.title);
                $.ajax({
                    url: '/api/admin/goodsAlbum/update',
                    type: "PUT",
                    data: {goodsId: CONST_GLOBAL_GOODS_ID, imgUrl:img},
                    dataType: "json",
                    success: function (data, textStatus, jqXHR) {
                        toastr.success(data.msg, data.title);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        toastr.error(errorThrown, textStatus);
                    }
                });
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
        return false;
    });

    $('#submitAttrLike').click(getAttrJson);
});
function getAttrJson() {
    var num = 0;
    if (typeof (CONST_GLOBAL_GOODS_ID) == "undefined") {
        alert("请先添加商品");
        return false;
    }
    var id = $('#typeId option:selected').val();
    if (id <= 0){
        toastr.warning("未选择分类", "警告");
        return false;
    }
    var check_array = [];
    var json_string = [];
    var json_params = [];
    var json_real_price = [];
    $("input", $("#attribute-list")).each(function () {
        if ($(this).attr('name') == "attr-checkbox") {
            if ($(this).prop("checked")){
                num += 1;
            }
            check_array.push($(this).prop("checked") ? 1 : 0);
            return;
        }
        if ($(this).attr('name') == "attr-text") {
            json_string.push(
                '"goodsId":' + CONST_GLOBAL_GOODS_ID + ',' +
                '"attrName":"' + $(this).attr("attrName") + '",' +
                '"attrId":' + $(this).attr("attrId") + ',' +
                '"attrValue":"' + $(this).attr("attrValue") + '",' +
                '"extraPrice":' + ($(this).val() == undefined || $(this).val() == '' ? 0 : $(this).val()));
            return;
        }
        if ($(this).attr('name') == "attrExtraPrice") {
            json_real_price.push(
                '"realExtraPrice":' + ($(this).val() == undefined || $(this).val() == '' ? 0 : $(this).val()) + ",");
            return;
        }


    });

    if (num == 0){
        toastr.warning("请选择规格","警告");
        return  false;
    }
    for (var i = 0; i < check_array.length; i++) {
            if (check_array.length === 1){
                json_params.push('[{' + json_string[i] + ',' + json_real_price[i] + '"attr_show":' + check_array[i] + '}]');
            } else {
                switch (i) {
                    case 0:
                        json_params.push('[{' + json_string[i] + ',' + json_real_price[i] + '"attr_show":' + check_array[i] + '},');
                        break;
                    case check_array.length - 1:
                        json_params.push('{' + json_string[i] + ',' + json_real_price[i] + '"attr_show":' + check_array[i] + '}]');
                        break;
                    default:
                        json_params.push('{' + json_string[i] + ',' + json_real_price[i] + '"attr_show":' + check_array[i] + '},');
                        break;
                }
            }
        }
    $.ajax(
        {
            url: ConfigAttributeLink.createUrl,
            type: "POST",
            data: {attrJson: json_params.join('').replace(/\n/g,'')},
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                toastr.success(data.msg, data.title);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    return false;
}


function getAttrList() {
    var id = $('#typeId option:selected').val();
    $.ajax(
        {
            url: ConfigAttribute.selectUrl,
            type: "GET",
            dataType: "json",
            data: {typeId: id},
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                data.data.map(function (category) {
                    categories.push('<div class="form-group">');
                    categories.push('<label class="col-sm-2 control-label" id="' + category.attrId + '">' + category.attrName + '</label>');
                    categories.push('<div class="col-sm-10">');
                    var attrValues = category.attrValues.split('\n');
                    if (attrValues && attrValues.length > 0) {
                        for (var i = 0; i < attrValues.length; i++) {
                            categories.push('<div class="form-inline">');
                            categories.push('<div class="checkbox col-sm-10" >');
                            categories.push('<label>');
                            categories.push('<input name="attr-checkbox"  type="checkbox" value="">'+ attrValues[i]+'');
                            categories.push('</label>');
                            categories.push('</div>');
                            categories.push('<div class="form-group">');
                            categories.push('<div class="col-sm-10">');
                            categories.push('<input type="hidden" name="attr-text"   class="form-control"  attrName="' + category.attrName.replace('\n','') + '" attrId="' + category.attrId + '" attrValue="' + attrValues[i] + '" required="" aria-required="true" minlength="1" maxlength="100000">');
                            categories.push('</div>');
                            categories.push('</div>');

                            categories.push('<div class="form-group">');
                            categories.push('<div class="col-sm-10">');
                            categories.push('<input type="hidden" name="attrExtraPrice"   class="form-control" required="" aria-required="true" minlength="1" maxlength="100000">');
                            categories.push('</div>');
                            categories.push('</div>');

                            categories.push('</div>');
                        }
                    }
                    categories.push('</div>');
                    categories.push('</div>');
                });
                $("#attribute-list").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

}

var CONST_GLOBAL_GOODS_ID;
function getContent() {
    return ue.getContent();
}

$(".goodsScreenPrice").change(function () {
    $(".profit").text(($(".goodsRealPrice").val() / $(".goodsScreenPrice").val()).toFixed(2) * 10);
});
$(".goodsRealPrice").change(function () {
    $(".profit").text(($(".goodsRealPrice").val() / $(".goodsScreenPrice").val()).toFixed(2) * 10);
});